package com.sin.j2me.wihd;

import javax.microedition.rms.RecordStoreException;

import com.sin.j2me.common.ExceptionHandle;
import com.sin.j2me.framework.NewDebug;
import com.sin.j2me.framework.SinFramework;
import com.sin.j2me.http.HttpRequest;
import com.sin.j2me.rms.RMSManager;
import com.sin.j2me.util.AsynchTask;
import com.sin.j2me.wihd.common.Constant;
import com.sin.j2me.wihd.common.Protocol;
import com.sin.j2me.wihd.model.User;
import com.sin.j2me.wihd.window.DetailWindow;
import com.sin.j2me.wihd.window.LoginWindow;
import com.sin.j2me.wihd.window.SigninWindow;
import com.sin.j2me.wihd.window.ThingsWindow;
import com.sin.j2me.wihd.window.Window;

public class FrameWork{
	public static User UO = new User();
	public static LoginWindow loginWindow = null;
	public static SigninWindow signinWindow = null;
	public static ThingsWindow thingsWindow = null;
	public static DetailWindow detailWindow = null;
	
//	private static FrameWork instance = null;
	
	private static RMSManager rms = null;
	
	private FrameWork(){

	}
	
//	public static FrameWork getInstance(){
//		if(instance == null)
//			instance = new FrameWork();
//		return instance;
//	}
	
	public static void start(MainMIDlet miDlet) {
		SinFramework.initFramework(miDlet);

		NewDebug.setShowOnLog(true);
		NewDebug.setShowOnScreen(true);
		NewDebug.setAutoClearLog(false);
		NewDebug.setLevel(NewDebug.LEVEL_ALL);
		
		try{
			rms = new RMSManager(Constant.rmsname);
			UO.setUsername(rms.getString(Protocol.P_USERNAME));
			UO.setPassword(rms.getString(Protocol.P_PASSWORD));
		}
		catch(Exception e){
			ExceptionHandle.handle(e);
			try {
				rms.clear();
			} catch (RecordStoreException e1) {
				ExceptionHandle.handle(e1);
			}
		}
		
		loginWindow = new LoginWindow();
		signinWindow = new SigninWindow();
		thingsWindow = new ThingsWindow();
		detailWindow = new DetailWindow();

		startWindow(loginWindow);
		
//		startCon();
	}
	
	public static int startWindow(Window window){
		return SinFramework.startDisplay(window.getWindow());
	}
	
	public static int finishWindow(Window window) {
		return SinFramework.finishDisplay(window.getWindow());
	}
	public static void exit(){
		try{
			rms.setString(Protocol.P_USERNAME, UO.getUsername());
			rms.setString(Protocol.P_PASSWORD, UO.getPassword());
			rms.close();
			
//			endCon();
		}
		catch(Exception e){
			ExceptionHandle.handle(e);
		}
		SinFramework.exit();
	}
	
	private static HttpRequest con = null;
	private static void startCon(){
		new AsynchTask(new Runnable() {
			public void run() {
				con = new HttpRequest();
				con.getHttpGetInputStream("http://www.baidu.com");
			}
		});
	}
	private static void endCon(){
		if(con != null)
			con.close();
		con = null;
	}
}
